<template>
  <div style="width:100%;height:100%;">
    <div class="map_title_box" style="height: 6%">
      <div class="map_title_innerbox">
        <div class="map_title">安保力量分布图</div>
      </div>
    </div>
    <div :class="isAllScreen?'full_screen' : ''" class="hp100 map_box">
      <div class="map" id="map"></div>
      <div id="panel"></div>
      <!-- 搜索 -->
      <div class="abs iptsearch" v-if="showSearch">
        <div class="input-item">
          <div class="input-item-prepend">
            <span class="input-item-text" style="width:8rem;color:#fff;">请输入关键字</span>
          </div>
          <input v-model="keywords" type="text" />
          <button @click="beginSearch()">搜索</button>
        </div>
      </div>
      <!-- 要素显示 -->
      <div v-if="showFeature" class="display_feature_box display_box cfff" style="right:0px;">
        <h4>设置地图显示要素</h4>
        <div id="map-features">
          <div class="input-item">
            <input
              type="checkbox"
              name="mapStyle"
              value="bg"
              :checked="features.indexOf('bg')>-1?true:false"
            />
            <span class="input-text">区域面</span>
          </div>
          <div class="input-item">
            <input
              type="checkbox"
              name="mapStyle"
              value="road"
              :checked="features.indexOf('road')>-1?true:false"
            />
            <span class="input-text">道路</span>
          </div>
          <div class="input-item">
            <input
              type="checkbox"
              name="mapStyle"
              value="building"
              :checked="features.indexOf('building')>-1?true:false"
            />
            <span class="input-text">建筑物</span>
          </div>
          <div class="input-item">
            <input
              type="checkbox"
              name="mapStyle"
              value="point"
              :checked="features.indexOf('point')>-1?true:false"
            />
            <span class="input-text">标注</span>
          </div>
        </div>
        <button
          @click="setMapFeatures()"
          class="pickbtn mt20 lh30"
          style="color:#000;width:100%;"
        >确定</button>
      </div>
      <!-- 主题 -->
      <div v-if="showTheme" class="display_theme_box display_box cfff" style="right:0px;">
        <h4>主题样式</h4>
        <div id="map-styles">
          <div v-for="(item,index) in themes" :key="index" class="input-item">
            <input
              type="radio"
              name="mapStyle"
              :value="item.value"
              @click="setMapStyle(item.value)"
            />
            <span>{{item.name}}</span>
          </div>
        </div>
      </div>
      <!--地图显示信息选择-->
      <div id="selectType" v-if="showBuss" class="display_type_box display_box">
        <el-checkbox
          :indeterminate="isIndeterminate"
          v-model="checkAll"
          @change="handleCheckAllChange"
        >全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="item in cities" :label="item.ID" :key="item.ID">{{item.MC}}</el-checkbox>
        </el-checkbox-group>

        <button id="pickbtn" @click="getPicks()" class="display_type_funct_box pickbtn">确定</button>
      </div>

      <!--地图工具栏-->
      <div class="map_tool_outbox">
        <span class="map_tool" @click="zoomFull()">
          <a class="map_tool_inner" title="全图"></a>
        </span>
        <span class="map_tool" @click="zoomAdd()">
          <a class="map_tool_inner" title="放大" style="background-position-x:-36px"></a>
        </span>
        <span class="map_tool" @click="zoomReduce()">
          <a class="map_tool_inner" title="缩小" style="background-position-x:-72px"></a>
        </span>

        <span class="map_tool" @click="userSpread()">
          <a
            class="map_tool_inner display_type_btn"
            title="用户分布"
            style="background-position-x:-180px"
          ></a>
        </span>
        <!-- <span class="map_tool">
           <a class="map_tool_inner city_chose_btn" title="城市定位" style="background-position-x:-432px"></a>
        </span>-->
        <span class="map_tool">
          <a
            class="map_tool_inner"
            @click="satellite()"
            title="卫星图层"
            style="background-position-x:-432px"
          ></a>
        </span>

        <span class="map_tool">
          <a
            class="map_tool_inner"
            @click="isShowSearch()"
            title="搜索"
            style="background-position-x:-468px"
          ></a>
        </span>
        <span @click="changeFeature()" class="map_tool">
          <a class="map_tool_inner" title="要素显示" style="background-position-x:-216px"></a>
        </span>
        <span class="map_tool">
          <a
            class="map_tool_inner"
            @click="changeThemes()"
            id="themes"
            title="默认主题"
            style="background-position-x:-288px"
          ></a>
        </span>
        <span class="map_tool" @click="clearAll()">
          <a class="map_tool_inner" title="清空" style="background-position-x:-396px"></a>
        </span>
        <span class="map_tool">
          <input type="text" id="txtCoord" style="width:150px;visibility:hidden" />
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import AMapLoader from "@amap/amap-jsapi-loader";
export default {
  data() {
    return {
      checkAll: false,
      checkedCities: [],
      cities: [],
      isIndeterminate: true,
      arr: [],
      scrollList: [],
      isAllScreen: false,
      centers: [
        {
          lng: 103.856602,
          lat: 30.688472,
          title: "中融集团温江分公司",
          icon: "./img/xxlogo.png",
          address: "四川省成都市温江区柳城街道德坤·新天地德昆·新天地",
          phone: "15882397196"
        }
      ],
      map: {},
      Amap: {},
      mapKey: "da0248ce65c46d26fed54c170ef3bfca",
      geocoder: {},
      pickBranch: [],
      showFeature: false,
      showTheme: false,
      showSearch: false,
      showBuss: false,
      features: ["building", "road"],
      themes: [
        { name: "标准", value: "normal" },
        { name: "幻影黑", value: "dark" },
        { name: "月光银", value: "light" },
        { name: "远山黛", value: "whitesmoke" },
        { name: "草色青", value: "fresh" },
        { name: "雅士灰", value: "grey" },
        { name: "涂鸦", value: "graffiti" },
        { name: "马卡龙", value: "macaron" },
        { name: "靛青蓝", value: "blue" },
        { name: "极夜蓝", value: "darkblue" },
        { name: "酱籽", value: "wine" }
      ],
      haveSate: false,
      keywords: "",
      addr: {},
      markers: [],
      layers:{}
    };
  },
  created: function() {
    let that = this;
    that.axios
      .post(`${that.$store.state.http}/list/getCustom`, {
        limit: 10,
        page: 1,
        para: {
          where: { BMLX: "05", SSGS: "001000000000000000000000000000" }
        }
      })
      .then(res => {
        that.cities = res.data.data;
        // that.cities = res.data.data.map(function(item) {
        //   return item.MC;
        // });
      });
  },
  mounted: function() {
    let that = this;
    AMapLoader.load({
      key: that.mapKey, // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "1.4.15", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        "AMap.ToolBar",
        "AMap.Scale",
        "AMap.Autocomplete",
        "AMap.PlaceSearch",
        "AMap.Weather",
        "AMap.Geocoder",
        "AMap.AdvancedInfoWindow"
      ] //插件列表
    })
      .then(AMap => {
        that.AMap = AMap;
        that.map = new AMap.Map("map", {
          zoom: 12,
          pitch: 50,
          zooms: [3, 20],
          expandZoomRange: true,
          showBuildingBlock: true,
          showLabel: true,
          mapStyle: "amap://styles/dark",
          center: [103.856602, 30.688472],
          features: that.features,
          viewMode: "2D",
          layers: [new AMap.TileLayer({})]
        });
        that.geocoder = new AMap.Geocoder({
          city: "全国", //城市设为北京，默认：“全国”
          radius: 100 //范围，默认：500
        });
        that.getMark(that.centers);
        that.getWeather('温江区');
      })
      .catch(() => {
      });
  },
  methods: {
    changeThemes() {
      this.showTheme = !this.showTheme;
      if(this.showTheme == true){
        this.showSearch = false;
        this.showBuss = false;
        this.showFeature = false;
      }
    },
    isShowSearch() {
      this.showSearch = !this.showSearch;
      if(this.showSearch == true) {
        this.showTheme = false;
        this.showBuss = false;
        this.showFeature = false;
      }
    },
    userSpread() {
      this.showBuss = !this.showBuss;
       if(this.showBuss == true) {
        this.showTheme = false;
        this.showSearch = false;
        this.showFeature = false;
      }
    },
    changeFeature(){
       this.showFeature = !this.showFeature;
       if(this.showFeature == true) {
        this.showTheme = false;
        this.showSearch = false;
        this.showBuss = false;
      }
    },
    clearAll(){
        this.showFeature = false;
        this.showTheme = false;
        this.showSearch = false;
        this.showBuss = false;
        this.map.remove(this.markers);
    },
    checkForm() {
      return false;
    },
    zoomAdd() {
      let that = this;
      that.map.setZoom(that.map.getZoom() + 1);
    },
    zoomReduce() {
      let that = this;
      that.map.setZoom(that.map.getZoom() - 1);
    },
    // 搜索
    beginSearch() {
      let that = this;
      that.map.setZoom(that.map.getZoom() + 1);
      var autoOptions = {
        city: "四川"
      };
      var placeSearch = new that.AMap.PlaceSearch(autoOptions);
      placeSearch.search(that.keywords, function(status, result) {
        // 搜索成功时，result即是对应的匹配数据
        if (result.poiList.pois[0]) {
          let pos = result.poiList.pois[0].location;
          that.map.setZoomAndCenter(16, [pos.lng, pos.lat]);
          that.addr = new that.AMap.Marker({
            position: new that.AMap.LngLat(pos.lng, pos.lat),
            title: result.poiList.pois[0].name
          });
          that.map.add(that.addr);
        } else {
          alert("地址不存在");
        }
      });
    },
    //天气预报
    async getWeather(city) {
      let that = this;
      var weather = new that.AMap.Weather();
      //查询实时天气信息, 查询的城市到行政级别的城市，如朝阳区、杭州市
      weather.getLive(city, function(err, data) {
        let title = data.city;
        if (!err) {
          data.title = title;
          that.$emit("getWeather", data);
        }
      })
      weather.getForecast(city,(error,res)=>{
          let arr = res.forecasts;
          // arr.shift();
          // console.log(arr)
          if (!error) {
          that.$emit("getForecast",arr);
        }
      })
    },
    satellite() {
      let that = this;
      that.haveSate = !that.haveSate;
      if (that.haveSate == true) {
        that.layers = new that.AMap.TileLayer.Satellite();
        that.map.add(that.layers);
      } else {
        that.map.remove(that.layers);
      }
    },
    //主题
    setMapStyle(val) {
      var styleName = "amap://styles/" + val;
      this.map.setMapStyle(styleName);
    },
    handleCheckAllChange(val) {
      let that = this;
      this.checkedCities = val
        ? this.cities.map(function(item) {
            return item.ID;
          })
        : [];
      this.isIndeterminate = false;
      that.pickBranch = this.checkedCities;
    },
    handleCheckedCitiesChange(value) {
      let that = this;
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.cities.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.cities.length;
      that.pickBranch = this.checkedCities;
    },
    getPicks() {
      this.showTheme = false;
      this.getGeoCode();
    },
    zoomFull() {
      this.isAllScreen = !this.isAllScreen;
    },
    getMark(centers) {
      let that = this;
      for (let i = 0; i < centers.length; i++) {
        var icon = new that.AMap.Icon({
          size: new that.AMap.Size(35, 35),
          image: "./img/baoanlogo.png",
          imageSize: new that.AMap.Size(35, 35)
        });
        let marker = new that.AMap.Marker({
          size: new that.AMap.Size(10, 10),
          position: new that.AMap.LngLat(centers[i].lng, centers[i].lat),
          icon: icon,
          title: centers[i].title
        });
        that.markers.push(marker);
        that.map.add(marker);
        
      }
    },
    getAddress(obj) {
      let that = this;
      return new Promise((res, rej) => {
        let lnglat = `${obj.lng},${obj.lat}`;
        that.geocoder.getAddress(lnglat, function(status, result) {
          if (status === "complete" && result.regeocode) {
            that.getWeather(result.regeocode.addressComponent.adcode);
            res(result);
          } else {
            rej(status);
          }
        });
      });
    },
    //地理位置转经纬度
    getGeoCode() {
      let that = this;
      that.axios
        .post(`${that.$store.state.http}/list/getCustom`, {
          page: 1,
          limit: 200,
          para: {
            where: {
              BMLX: "03",
              BMID: { $in: that.pickBranch },
              SSGS: "001000000000000000000000000000"
            }
          }
        })
        .then(res => {
          that.geoCode(res.data.data);
        });
    },
    //设置地图显示要素
    setMapFeatures() {
      var features = [];
      var inputs = document.querySelectorAll("#map-features input");
      inputs.forEach(function(input) {
        if (input.checked) {
          features.push(input.value);
        }
      });
      this.features = features;
      this.map.setFeatures(features);
      this.showFeature = false;
    },
    getRelatePeople(id) {
    },
    //点击标记点
    geoCode(arr) {
      let that = this;
      that.map.remove(that.markers);
      that.markers = [];
      arr.map(function(item) {
        that.geocoder.getLocation(item.DZ, function(status, result) {
          if (status === "complete" && result.geocodes.length) {
            for (var i = 0; i < result.geocodes.length; i += 1) {
              var addmarker = async function(myicon) {
                let marker = await new that.AMap.Marker({
                  map: that.map,
                  position: result.geocodes[i].location,
                  title: item.MC,
                  icon: myicon,
                  extData: { ID: item.ID, MC: item.MC }
                });
                that.markers.push(marker);
                marker.on("click", function(res) {
                  let obj = { lng: res.lnglat.lng, lat: res.lnglat.lat };
                  that.getAddress(obj).then(re => {
                    that.getWeather(re.regeocode.addressComponent.adcode, res);
                    that.$emit("getJF", res.target.w.extData.MC);
                    that.$emit("getDWID", res.target.w.extData.ID);
                    // that.getRelatePeople(res.target.w.extData.ID);
                  });
                });
              };
              let myicon = {};
              switch (item.BMID) {
                //xiaoyuan
                case "001003002001000000000000000000": {
                  myicon = new that.AMap.Icon({
                    size: new that.AMap.Size(35, 35), // 图标尺寸
                    image: "./img/xxlogo.png", // Icon的图像
                    imageSize: new that.AMap.Size(35, 35) // 根据所设置的大小拉伸或压缩图片
                  });
                  addmarker(myicon);
                  break;
                }
                //yinhang
                case "001003002002000000000000000000": {
                  myicon = new that.AMap.Icon({
                    size: new that.AMap.Size(35, 35), // 图标尺寸
                    image: "./img/yhlogo.png", // Icon的图像
                    imageSize: new that.AMap.Size(35, 35) // 根据所设置的大小拉伸或压缩图片
                  });
                  addmarker(myicon);
                  break;
                }
                //yuelecahngsuo
                case "001003002003000000000000000000": {
                  myicon = new that.AMap.Icon({
                    size: new that.AMap.Size(35, 35), // 图标尺寸
                    image: "./img/yllogo.png", // Icon的图像
                    imageSize: new that.AMap.Size(35, 35) // 根据所设置的大小拉伸或压缩图片
                  });
                  addmarker(myicon);
                  break;
                }
                //gongan
                case "001003001001000000000000000000": {
                  myicon = new that.AMap.Icon({
                    size: new that.AMap.Size(35, 35), // 图标尺寸
                    image: "./img/jclogo.png", // Icon的图像
                    imageSize: new that.AMap.Size(35, 35) // 根据所设置的大小拉伸或压缩图片
                  });
                  addmarker(myicon);
                  break;
                }
                //wangge
                case "001003001002000000000000000000": {
                  myicon = new that.AMap.Icon({
                    size: new that.AMap.Size(35, 35), // 图标尺寸
                    image: "./img/wglogo.png", // Icon的图像
                    imageSize: new that.AMap.Size(35, 35) // 根据所设置的大小拉伸或压缩图片
                  });
                  addmarker(myicon);
                  break;
                }
                default: {
                  myicon = new that.AMap.Icon({
                    size: new that.AMap.Size(35, 35), // 图标尺寸
                    image: "./img/qylogo.png", // Icon的图像
                    imageSize: new that.AMap.Size(35, 35) // 根据所设置的大小拉伸或压缩图片
                  });
                  addmarker(myicon);
                  break;
                }
              }
            }
            that.map.add(that.markers);
            // that.map.setFitView(that.markers);
          }
        });
        // return item.DZ
      });
    }
  }
};
</script>

<style>
.map_box {
  height: "95%";
  width: "100%";
}
.full_screen {
  z-index: 4;
  position: fixed;
  height: 100vh;
  width: 100vw;
  top: 0;
  left: 0;
}
.el-checkbox__label {
  color: #fff;
}
</style>